import { createRouter, createWebHashHistory,createWebHistory } from 'vue-router'
import Layout from '@/view/layout/index.vue'
const routes = [

  // 前两个测试页面  没用的时候删掉
  {
    path: '/',
    redirect: {
      name: 'home'
    }
  },
  {
    name: 'home',
    path: '/home',
    component: () => import('@/view/home.vue'),
    meta: {
      title: '红手指'
    }
  },

  // 主要页面
  {
    path: '',
    component: Layout,
    redirect: 'home',
    children: [
      // 所有页面写在这里
      {
        path: 'goodsList',
        component: () => import('@/view/goodsList/goodsList.vue'),
        name: 'goodsList',
        meta: { title: '商品列表' }
      }
    ]
  },

  // 登录页  用于开发的时候进行登录
  {
    name: 'login',
    path: '/login',
    component: () => import('@/view/login.vue'),
    meta: {
      title: '登录'
    }
  },

  {
    name: 'error',
    path: '/error',
    component: () => import('@/view/error.vue'),
    meta: {
      title: '发生错误'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/error'
  }
]

const router = createRouter({
  routes,
  history: createWebHistory(),
  scrollBehavior() {
    return {
      top: 0
    }
  }
})

router.beforeEach((to, from, next) => {
  const title = to?.meta?.title
  if (title) {
    document.title = title as string
  }
  if (to.matched.length === 0) next('/error')
  next()
})

export default router
